package com.qyoung.controller;

import com.qyoung.service.UserService;
import com.qyoung.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(urlPatterns = "/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();  //让session失效
        resp.sendRedirect("index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserService userService = new UserServiceImpl();
        boolean login = userService.login(username, password);
        if (login) {
            HttpSession session = req.getSession();
            session.setAttribute("username",username);
            session.setAttribute("password",password);
            resp.sendRedirect("success.jsp");
        }else {
            //使用Cookie记录用户名信息
            Cookie cookie = new Cookie("username",username);
            resp.addCookie(cookie);
            resp.sendRedirect("fail.html");
        }
    }
}
